#-*- coding:utf-8 -*-

import socket as line
from flask import *
import shutil
import time
import ast
import os

__verson__ = '1.8.2'

data = {}
token = ['123456']
port = 10307
dfle = '.\data'

def ToIP(domain):
    addr = line.getaddrinfo(domain, 'http')
    return addr[0][4][0]

def HostIP():
    try:
        s = line.socket(line.AF_INET, line.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:s.close()
    return ip

def GetTime():
    ti = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    return ti

def TimeStamp(ti):
    timeArray = time.strptime(ti, "%Y-%m-%d %H:%M:%S")
    stamp = int(time.mktime(timeArray))
    return stamp

def WriteFiles(key, val, dfle=dfle):
    if not os.path.exists(dfle):os.mkdir(dfle)
    dat = GetTime()+'    ==    '+val+'\n'
    with open(os.path.join(dfle, key+'.cot'), 'a') as f:
        f.write(dat)

def FindLast(path):
    with open(path) as f:
        buf = f.readline()
        while True:
            now = f.readline()
            if now == '':break
            else:buf = now
    return buf.split('==')[1].strip()

def WriteToken(token, dfle=dfle):
    if not os.path.exists(dfle):os.mkdir(dfle)
    with open(os.path.join(dfle, 'token.toc'), 'a') as t:
        t.write(token+'\n')

def ReadToken(token, dfle=dfle):
    if not os.path.exists(dfle):os.mkdir(dfle)
    if not os.path.exists(os.path.join(dfle, 'token.toc')):return False
    with open(os.path.join(dfle, 'token.toc')) as t:
        while True:
            buf = t.readline()
            if buf != '':token.append(buf.strip())
            else:break
    return True

def ReadFiles(dat=data,dfle=dfle,key=None):
    if not os.path.exists(dfle):os.mkdir(dfle)
    ke = os.listdir(dfle)
    keys = []
    for k in ke:
        if k[-4:] == '.cot':keys.append(k)
    if key != None:
        if not key+'.cot' in keys:return False
        dat[key] = os.path.join(dfle, key+'.cot')
        return True
    else:
        for k in keys:dat[k[:-4]] = FindLast(os.path.join(dfle, k))
        return True

class Dfles:
    def __init__(self, files, open=False):
        if not os.path.exists(files):os.mkdir(files)
        self.dfle = files
        self.open = open
        self.data = {}
        self.token = []
        ReadFiles(self.data, self.dfle)
        ReadToken(self.token, self.dfle)
    
    def update(self, key, value):
        print(key, value)
        self.data[key] == value
        WriteFiles(key, value, self.dfle)
    
    def getdata(self, key):
        return self.data.get(key, 'None')
    
    def addtoken(self, token):
        self.token.append(token)
        WriteToken(token, self.dfle)

app = Flask(__name__)
tic = Dfles('.\\data')

@app.route("/data/update/", methods=['POST'])
def updata():
    req = dict(request.form)
    ip = request.remote_addr
    if ip != '127.0.0.1' and tic.open == False:
        if ip != HostIP():
            if not req.get('token', 'none') in tic.token:return str({'error':'token'})
    if req.get('key', 'None') == 'None' or req.get('value', 'None') == 'None':return str({'error':'data'})
    tic.update(req.get('key'), req.get('value'))
    return str({'rezult':'True'})

@app.route("/data/get/", methods=['POST'])
def get():
    req = dict(request.form)
    ip = request.remote_addr
    if ip != '127.0.0.1' and tic.open == False:
        if ip != HostIP():
            if not req.get('token', 'none') in tic.token:return str({'error':'token'})
    if req.get('key', 'None') == 'None':return str({'error':'key'})
    return str({'value':tic.getdata(req.get('key'))})

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=port)